from django.conf import settings
from django.shortcuts import render, redirect

from app01.utils.md5 import gen_md5
from rbac.service.init_permission import init_permission
from app01 import models


# Create your views here.
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    user = models.UserInfo.objects.filter(username=user, password=gen_md5(pwd)).first()
    if not user:
        return render(request, 'login.html', {'msg': '用户名或密码错误'})
    request.session['user_info'] = {'id': user.id, 'username': user.username}
    # 用户权限信息的初始化
    init_permission(user, request)

    return redirect('/index/')


def logout(request):
    """
    注销
    :param request:
    :return:
    """
    request.session.delete()

    return redirect('/login/')


def index(request):
    return render(request, 'index.html')
